<template>
  <scroll class="suggest" :data="result" :beforeScroll="beforeScroll" :pullup="true" @scrollToEnd="searchMore" ref="suggest"
          @beforeScroll="listBeforeScroll">
    <ul class="suggest-list">
      <li @click="selectItem(item)" class="suggest-item" v-for="item in result">
        <div class="icon">
          <i :class="getIconCls(item)"></i>
        </div>
        <div class="name">
          <p class="text" v-html="getDisplayName(item)"></p>
        </div>
      </li>
      <!--<loading v-show="hasMore" title=""></loading>-->
    </ul>
    <div v-show="!hasMore && !result.length" class="no-result-wrapper">
      <no-result title="抱歉，暂无搜索结果"></no-result>
    </div>
  </scroll>
</template>

<script>
  import {search} from 'api/search.js';
  import {ERR_OK} from 'api/config.js';
  import {createSong} from 'common/js/song.js';
  import {Singer} from 'common/js/singer.js';
  import Scroll from '../base/scroll/scroll.vue';
  import NoResult from '../base/no-result/no-result.vue';
  import {mapMutations, mapActions} from 'vuex';

  const PERPAGE = 20;
  const TYPE_SINGER = 'singer';
  export default {
    components: {Scroll, NoResult},
    props: {
      query: {type: String, default: ''},
      showSinger: {type: Boolean, default: true}
    },
    data () {
      return {
        page: 1,
        hasMore: false,
        beforeScroll: true,
        result: []
      };
    },
    methods: {
      getIconCls (item) {
        if (item.type === TYPE_SINGER) {
          return 'icon-mine';
        } else {
          return 'icon-music';
        }
      },
      getDisplayName (item) {
        if (item.type === TYPE_SINGER) {
          return item.singername;
        } else {
          return `${item.name}-${item.singer}`;
        }
      },
      selectItem (item) {
//        console.log(item);
        if (item.type && item.type === TYPE_SINGER) { // 点击歌手
          let singer = new Singer(item.singermid, item.singername);
          this.setSinger(singer);
          this.$router.push({
            path: `/search/${singer.id}`
          });
        } else { // 点击歌
          this.insertSong(item);
        }
        this.$emit('select');
      },
      searchMore () {
        if (!this.hasMore) {
          return;
        }
        this.page++;
        this.search();
      },
      search () {
        this.hasMore = true;
        search(this.query, this.page, this.showSinger, PERPAGE).then(res => {
//          console.log(res);
          if (res.code === ERR_OK) {
            let r = this._genResult(res.data);
            if (this.page === 1) {
              this.result = r;
            } else {
              this.result = this.result.concat(r);
            }
            this._isHasMore(res.data);
//            console.log(this.result);
          } else {
            console.log('search 出错');
          }
        }).catch(() => {
          console.log('search异常');
        });
      },
      _isHasMore (data) {
        if (!data.song || !data.song.list || data.song.list.length === 0) {
          this.hasMore = false;
          return;
        }
        let maxP = Math.ceil(data.song.totalnum / data.song.curnum);
        if (data.song.curpage >= maxP) {
          this.hasMore = false;
        } else {
          this.hasMore = true;
        }
      },
      _genResult (data) {
        let ret = [];
        if (data.zhida && data.zhida.singerid) {
          ret.push({...data.zhida, ...{type: TYPE_SINGER}});
        }
        if (data.song) {
          ret = ret.concat(this._normalizeSongs(data.song.list));
        }
        return ret;
      },
      _normalizeSongs (list) {
        let ret = [];
        list.forEach((musicData) => {
          if (musicData.songid && musicData.albummid) {
            ret.push(createSong(musicData));
          }
        });
        return ret;
      },
      listBeforeScroll () {
        this.$emit('listScroll');
      },
      refresh () {
        this.$refs.suggest.refresh();
      },
      ...mapMutations({
        'setSinger': 'SET_SINGER'
      }),
      ...mapActions({
        'insertSong': 'insertSong'
      })
    },
    watch: {
      query () {
        this.search();
      }
    }
  };
</script>

<style lang="less" scoped="">
  @import "~common/css/variable.less";
  @import "~common/css/mixin.less";

  .suggest {
    height: 100%;
    overflow: hidden;
    .suggest-list {
      padding: 0 30px;
      .suggest-item {
        display: flex;
        align-items: center;
        padding-bottom: 20px;
      }
      .icon {
        flex: 0 0 30px;
        width: 30px;
        [class^="icon-"] {
          font-size: 14px;
          color: @color-text-d;
        }
      }
      .name {
        flex: 1;
        font-size: @font-size-medium;
        color: @color-text-d;
        overflow: hidden;
        .text {
          .no-wrap()
        }
      }
    }
    .no-result-wrapper {
      position: absolute;
      width: 100%;
      /*top: 50%;*/
    }
  }

</style>
